<template>
  <div class="flexContent">
    <div class="searchBox">

      <el-form class="demo-form-inline" label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="门店">
                  <el-select @click.native="getShopEasy" v-model="storeId" size="small" clearable style="width: 95%"
                    filterable placeholder="请选择..." popper-class="eloption">
                    <el-option v-for="item in easyshopList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品名称">
                  <el-input v-model.trim="name" clearable style="width: 95%" placeholder="商品名称/条码"
                    @keyup.enter.native="searchFn" />
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品类型">
                  <el-select v-model="type" popper-class="eloption" clearable style="width: 95%" filterable
                    placeholder="请选择">
                    <el-option value="0" label="标品" />
                    <el-option value="2" label="自营" />
                    <el-option value="4" label="期初" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="10" :xl="6">
                <el-form-item label="兑换时间">
                  <el-date-picker clearable v-model="date" style="width: 95%" type="daterange" unlink-panels
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetFn" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" @click="exportSell" v-has="'exchangegoods_export'">导出</el-button>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable1"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="100%"
          size="medium" align="center">
          <vxe-column type="seq" width="80" title="序号" />
          <vxe-column field="storeName" title="门店名称" :min-width="elTableAdaptationWidth('storeName', shopList)" />
          <vxe-column field="name" title="商品名称" :min-width="elTableAdaptationWidth('name', shopList)" />
          <vxe-column field="barCode" title="商品条码" min-width="200" />
          <vxe-column field="type" title="类型" min-width="120">
            <template v-slot="{ row }">
              <span v-if="row.type === '0'">标品</span>
              <span v-if="row.type === '1'">非标品</span>
              <span v-if="row.type === '2'">自营</span>
              <span v-if="row.type === '3'">临时</span>
              <span v-if="row.type === '4'">期初</span>
            </template>
          </vxe-column>
          <vxe-column field="count" title="兑换数量" min-width="120" />
          <vxe-column field="createTime" title="兑换时间" min-width="150">
            <template v-slot="{ row }">
              <span>{{ row.createTime | parseTime("YYYY-MM-DD HH:mm:ss") }}</span>
            </template>
          </vxe-column>
          <vxe-column field="userName" title="操作人" min-width="120" />
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,-> , sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import { getExchangeList, exportGoodsExchange, getShopEasy } from "@/api/shop";
export default {
  name: "GoodsInfo",
  data() {
    return {
      isSearch: false,

      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      name: "",
      type: "",
      openTime: '',
      endTime: '',
      storeId: '',
      easyshopList: [],
      shopList: [],
      date: []
    };
  },
  created() {
    this.getExchangeList();
  },
  methods: {
    async getShopEasy() {
      const res = await getShopEasy();
      if (res.code === 200) {
        console.log('门店', res.data.store);
        this.easyshopList = res.data.store;
      }
    },
    async getExchangeList() {
      if (!this.isSearch) {
        this.name = "";
        this.type = "";
        this.openTime = ''
        this.endTime = ''
        this.storeId = ''
      }
      const res = await getExchangeList({
        ...this.page,
        name: this.name,
        endTime: this.endTime,
        openTime: this.openTime,
        type: this.type,
        storeId: this.storeId
      });
      if (res.code === 200) {
        console.log(res);
        const result = res.data;
        this.shopList = result.list;
        this.page.pageSize = result.pageSize;
        this.page.pageNum = result.pageNum;
        this.page.total = result.total;
        console.log("shopList", this.shopList);
        const $table = this.$refs.xTable1
        $table.loadData(this.shopList);
      } else {
        // this.$message.error(res.message);
      }
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      this.getExchangeList();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page.pageNum = val;
      this.getExchangeList();
    },

    async searchFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.openTime = this.date?.length ? this.date[0] : '';
      this.endTime = this.date?.length ? this.date[1] : '';
      this.isSearch = true;
      this.getExchangeList();
    },
    resetFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.name = "";
      this.type = "";
      this.openTime = ''
      this.endTime = ''
      this.storeId = ''
      this.isSearch = false;
      this.selectedOptions = [];
      this.getExchangeList();
    },
    exportSell() {
      this.$confirm(`确认导出数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let { name, type, openTime, endTime, storeId } = this;
        let reqObj = { name, type, openTime, endTime, storeId };
        let response = await exportGoodsExchange(reqObj);
        let res = null;
        if (response.data.type === "application/json") {
          const reader = new FileReader();  //创建一个FileReader实例
          reader.readAsText(response.data, 'utf-8'); //读取文件,结果用字符串形式表示
          reader.onload = () => {//读取完成后,**获取reader.result**
            res = JSON.parse(reader.result)
            if (res.code !== 200) {
              this.$message.error(res.message);
              return;
            }
          }
        } else {
          const fileName = decodeURIComponent(response.headers["content-disposition"].split(";")[1].split("''")[1]);
          FileSaver.saveAs(response.data, fileName);
        }
      })
    },

  },
};
</script>

<style lang="scss" scoped></style>
